<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Soal extends CI_Controller {

	public function __construct(){
		parent::__construct();
		$this->load->model('login_model','l_db');
		$this->load->model('soal_model','get_db');
	}

	/**
	 * Index Page for this controller.
	 */
	public function index()
	{
		if($this->session->userdata('username')){
			$header['menu'] = $this->l_db->generate_menu();
			$data['grid'] 	= $this->get_db->get_list()->result_array();	
			$footer['js'][] = "<script type='text/javascript'>var base_url = '".base_url().index_page()."';</script>";
			$footer['js'][] = '<script src="'.app_asset_url().'js/app/grid_soal.js"></script>';		
			$this->load->view('header_view',$header);
			$this->load->view('soal_view',$data);
			$this->load->view('footer_view',$footer);
		}else{
			$this->session->set_flashdata( 'message', array( 'title' => 'Error', 'content' => 'Please login !', 'type' => 'alert alert-error' )); 
			redirect();
		}
	}

	public function add_bab()
	{
		if($this->session->userdata('username')){
			$header['menu'] = $this->l_db->generate_menu();
			$data['grid'] = $this->get_db->get_list()->result_array();
			$data['cat'] 	= $this->get_db->get_cat()->result_array();
			$data['jenjang'] 	= $this->get_db->get_jenjang()->result_array();
			$data['kelas'] 	= $this->get_db->get_kelas()->result_array();
			$data['pelajaran'] 	= $this->get_db->get_cat()->result_array();
			$data['bab'] 	= $this->get_db->get_bab()->result_array();
			$footer['js'][] = '<script src="'.app_asset_url().'js/app/soal.js"></script>';
			$this->load->view('header_view',$header);
			$this->load->view('add_bab_view',$data);
			$this->load->view('footer_view',$footer);
		}else{
			$this->session->set_flashdata( 'message', array( 'title' => 'Error', 'content' => 'Please login !', 'type' => 'message' )); 
			redirect();
		}
	}
	
	public function add_soal()
	{
		if($this->session->userdata('username')){
			$header['menu'] = $this->l_db->generate_menu();
			$data['grid'] = $this->get_db->get_list()->result_array();
			$data['cat'] 	= $this->get_db->get_cat()->result_array();
			$data['jenjang'] 	= $this->get_db->get_jenjang()->result_array();
			$data['kelas'] 	= $this->get_db->get_kelas()->result_array();
			$data['pelajaran'] 	= $this->get_db->get_cat()->result_array();
			$data['bab'] 	= $this->get_db->get_bab()->result_array();
			$footer['js'][] = '<script src="'.app_asset_url().'js/app/soal.js"></script>';
			$this->load->view('header_view',$header);
			$this->load->view('add_soal_view',$data);
			$this->load->view('footer_view',$footer);
		}else{
			$this->session->set_flashdata( 'message', array( 'title' => 'Error', 'content' => 'Please login !', 'type' => 'message' )); 
			redirect();
		}
	}

	public function edit_soal($id = false)
	{
		if($this->session->userdata('username')){
			$header['menu'] = $this->l_db->generate_menu();
			$data['data'] = $this->get_db->get_data($id)->row_array();
			$data['cat'] 	= $this->get_db->get_cat()->result_array();
			$data['jenjang'] 	= $this->get_db->get_jenjang()->result_array();
			$data['kelas'] 	= $this->get_db->get_kelas()->result_array();
			$data['pelajaran'] 	= $this->get_db->get_cat()->result_array();
			$data['bab'] 	= $this->get_db->get_bab()->result_array();
			$footer['js'][] = '<script src="'.app_asset_url().'js/app/soal.js"></script>';
			$this->load->view('header_view',$header);
			$this->load->view('edit_soal_view',$data);
			$this->load->view('footer_view',$footer);
		}else{
			$this->session->set_flashdata( 'message', array( 'title' => 'Error', 'content' => 'Please login !', 'type' => 'message' )); 
			redirect();
		}
	}		
	
	public function list_soal($id = false)
	{
		if($this->session->userdata('username')){
			$header['menu'] = $this->l_db->generate_menu();
			$data['grid'] 	= $this->get_db->get_list_soal($id)->result_array();
			// $kid = $data['grid'][0]['kelas_id'];
			// $pid = $data['grid'][0]['pel_id'];
			$footer['js'][] = "<script type='text/javascript'>var base_url = '".base_url().index_page()."';</script>";
			$footer['js'][] = '<script src="'.app_asset_url().'js/app/grid_soal.js"></script>';		
			$this->load->view('header_view',$header);
			$this->load->view('list_soal_view',$data);
			$this->load->view('footer_view',$footer);
		}else{
			$this->session->set_flashdata( 'message', array( 'title' => 'Error', 'content' => 'Please login !', 'type' => 'message' )); 
			redirect();
		}
	}	
	
	public function save($id = false){
		if($_POST){			
			// Update
			if($id){		
				if($this->get_db->do_update($id,$_POST)) $this->session->set_flashdata( 'message', array( 'title' => 'Info', 'content' => 'Berhasil merubah !', 'type' => 'alert alert-success' )); 
				else $this->session->set_flashdata( 'message', array( 'title' => 'Error', 'content' => 'Gagal merubah !', 'type' => 'alert alert-error' )); 
				redirect('soal');
			}else{
				if($this->get_db->do_add($_POST)) $this->session->set_flashdata( 'message', array( 'title' => 'Info', 'content' => 'Berhasil menambah !', 'type' => 'alert alert-success' )); 
				else $this->session->set_flashdata( 'message', array( 'title' => 'Error', 'content' => 'Gagal menambah !', 'type' => 'alert alert-error' )); 
				redirect('soal');			
			}
		}else{
			die('No direct access!');
		}
	}

	public function delete($id = false){
		if($id){
			$ids = explode('_',$id);
			$tid = count($ids);
			if($tid == 1){
				if($this->get_db->do_delete($id))  $this->session->set_flashdata( 'message', array( 'title' => 'Info', 'content' => 'Berhasil menghapus !', 'type' => 'alert alert-success' )); 
				else $this->session->set_flashdata( 'message', array( 'title' => 'Error', 'content' => 'Gagal menghapus !', 'type' => 'alert alert-error' )); 
			}else{
				$success = 0;
				foreach($ids as $i){
					if($this->get_db->do_delete($i)) $success++;
				}
				if($success > 0)  $this->session->set_flashdata( 'message', array( 'title' => 'Info', 'content' => $success.' dari '.$tid.' berhasil dihapus !', 'type' => 'alert alert-success' )); 
				else  $this->session->set_flashdata( 'message', array( 'title' => 'Error', 'content' => 'Gagal menghapus !', 'type' => 'alert alert-error' )); 
			}
			redirect('soal');
		}else{
			die('No direct access!');		
		}
	}

	private function _remove_htmlspecialchar($content){
		return preg_replace("/&#?[a-z0-9]{2,8};/i","",$content);
	}

	public function upload_soal(){
		if($this->session->userdata('username')){
			$header['menu'] = $this->l_db->generate_menu();
			$data['grid'] = $this->get_db->get_list()->result_array();
			$data['jenjang'] 	= $this->get_db->get_jenjang()->result_array();
			$data['kelas'] 	= $this->get_db->get_kelas()->result_array();
			$data['pelajaran'] 	= $this->get_db->get_cat()->result_array();
			$data['bab'] 	= $this->get_db->get_bab()->result_array();
			$footer['js'][] = '<script src="'.app_asset_url().'js/app/soal.js"></script>';
			$this->load->view('header_view',$header);
			$this->load->view('upload_soal_view',$data);
			$this->load->view('footer_view',$footer);
		}else{
			$this->session->set_flashdata( 'message', array( 'title' => 'Error', 'content' => 'Please login !', 'type' => 'message' )); 
			redirect();
		}
	}

	public function upload(){
		$this->load->helpers('excel_reader2');
		if(!empty($_FILES['userfile']['tmp_name'])) {
			if($_FILES['userfile']['type']=='application/force-download'||$_FILES['userfile']['type']=='application/vnd.ms-excel'||$_FILES['userfile']['type']=='application/octet-stream'){
				$data = new Spreadsheet_Excel_Reader($_FILES['userfile']['tmp_name']);				
				$row = $data->rowcount($sheet_index=0);  // membaca jumlah baris dari data excel
				$start_row 	= 2; 	// Start row data
				$end_col 	= 8; 	// End of col
				$good 		= 0; 	// Count success insert
				$bad 		= 0;	// Count failed insert			
				$error_logs = array();	// Capture error logs, and write to txt file			

				// Reference Initialization				
				// ================================================================================				
				$is_publish = array('YES','NO');
				$jawaban = array('A','B','C','D','E');

				// List of column that not need to upper case
				$do_not_upper = array(12,54,55); // [address,prepared by,remark]				
				// ================================================================================

				for ($i=$start_row; $i<=$row; $i++)
				{
					$param = array();
					for($j=1; $j<=$end_col; $j++){								
						// fix utf 8, trim, replace html tags and replace single quote character
						$val = mb_convert_encoding($data->val($i,$j), 'UTF-8', 'UTF-8'); // Remove invalid UTF-8 character !!
						$val = $this->_remove_htmlspecialchar(strip_tags(trim(str_replace("'",'',$val))));	
						if(($val != '') && !in_array($j,$do_not_upper)) $val = strtoupper($val); // Upper column yang sesuai setting 
						switch ($j){
							case 2:
								if(($val == '')){ $error_logs[$i]['text'] = 'Soal tidak boleh kosong'; continue 2;}
								$param['pertanyaan'] = $val;
							break;								

							case 3:
								if(($val == '')){ $error_logs[$i]['text'] = 'Pilihan A tidak boleh kosong'; break 2;}
								$param['pilihan_a'] = $val;
							break;

							case 4:
								if(($val == '')){ $error_logs[$i]['text'] = 'Pilihan B tidak boleh kosong'; break 2;}
								$param['pilihan_b'] = $val;
							break;

							case 5:
								if(($val == '')){ $error_logs[$i]['text'] = 'Pilihan C tidak boleh kosong'; break 2;}
								$param['pilihan_c'] = $val;
							break;

							case 6:
								if(($val == '')){ $error_logs[$i]['text'] = 'Pilihan D tidak boleh kosong'; break 2;}
								$param['pilihan_d'] = $val;
							break;

							case 7:
								if(($val == '')){ $error_logs[$i]['text'] = 'Pilihan E tidak boleh kosong'; break 2;}
								$param['pilihan_e'] = $val;
							break;

							case 8:
								if(($val == '')){ $error_logs[$i]['text'] = 'Jawaban tidak boleh kosong'; break 2;}
								if(!in_array($val,$jawaban)) {$error_logs[$i]['text'] = 'Jawaban tidak sesuai, Opsi tersedia ['.implode(',',$jawaban).']'; break 2;}
								$param['jawaban'] = $val;
							break;

							case 9:
								if(($val == '')){ 
									$param['publish'] = 'YES'; // Jika kosong, default Y
								}else{
									if(!in_array($val,$is_publish)) {$error_logs[$i]['text'] = 'Opsi tidak sesuai, Opsi tersedia ['.implode(',',$is_publish).']'; break 2;}
									$param['publish'] = $val;
								}
							break;
						}
					}
					$param['bab_id'] = isset($_POST['bab_id']) ? $_POST['bab_id'] : null;	
					if(!isset($error_logs[$i]['text'])){	
						if($this->get_db->do_add($param)){
							$good++;						
						}else{ 
							$error_logs[$i]['text'] = 'Failed to save';
							$bad++; 						
						}
					}else{
						$bad++;
					}
						
				}
				if($bad == 0){
					$this->session->set_flashdata( 'message', array( 'title' => 'Info', 'content' => "$good row(s) uploaded successfully <br/> $bad of row(s) failed. ", 'type' => 'alert alert-success' )); 
					redirect('soal');
				}else{
					$username 		= str_replace(' ', '_', $this->session->userdata('NAMA'));
					$date_upload 	= date('F-d-Y-H-i-s');
					$time_log 		= date('F-d-Y H:i:s');
					$basepath 		= str_replace('system/','',BASEPATH);
					$file_log 		= $basepath.'backend/assets/log_upload/log_soal_'.$username.'-'.$date_upload.'.txt';
					$file_log_download 	= base_url().index_page().'/soal/view_log/log_soal_'.$username.'-'.$date_upload.'.txt';
					$link_download 		= anchor('soal/download_log/log_soal_'.$username.'-'.$date_upload.'.txt','here');
					
	                if(!empty($file_log)){
						$fh = fopen($file_log, 'w+');
						$data_log = "";
						foreach($error_logs as $idx=>$log){
							$data_log .= "[".$time_log."] [".$username."] [ Row : ".$idx." ] ".$log['text']."\r\n";
						}
						fwrite($fh, $data_log);
						fclose($fh);
					}

					// If any error occured. Show log file.
					// echo "{success:true,msg:' $good row(s) uploaded successfully <br/> $bad of row(s) failed. <br/> Download log $link_download ', logs:'".$file_log_download."'}";
					$this->session->set_flashdata( 'message', array( 'title' => 'Info', 'content' => "$good row(s) uploaded successfully <br/> $bad of row(s) failed. <br/> Download log $link_download ", 'type' => 'alert alert-success' )); 
					redirect('soal');
				}		
			}else{
				$this->session->set_flashdata( 'message', array( 'title' => 'Error', 'content' => 'Invalid file extension, accept .xls files only !!', 'type' => 'alert alert-error' )); 
				redirect('soal');
			}
		}else{
			$this->session->set_flashdata( 'message', array( 'title' => 'Error', 'content' => 'No file found !', 'type' => 'alert alert-error' )); 
			redirect('soal');
		}

	}
}
